var textBox = new Array();
var textPlace  =   new Array();
var time = new Time();
var play = new Play();
var menu = new Menu();
var index = new IndexStage();
var dragAudio = new Audio('sound/ClickPage.mp3');
var text = 'english';
var img = 'images/Play/default.png';
var textQ = "What is this?";
var textSay = "It's an ";

//Backgournd Music
var bgmusic = new Audio('sound/MusicBox.mp3');
bgmusic.loop = true;

//Index Stage
function IndexStage(){
    var _self = this;
    this.create = function(){
        $("#stage").append($(indexStage).html());
        $("#stage").css({
            webkitOpacity:'1.0',
            webkitTransform: 'translate3d(0px,0px,0px)',
            });
        var _flagCloud=true;
        var _flagHair=true;
        var _flagKid=true;
        var _flagLogo=true;
        var t = setTimeout(function(){
            $(".cloudSmall").bind('webkitAnimationEnd',function(){
                if(_flagCloud==true){
                    $(".cloudSmile").css('-webkit-animation-name','bigFly');
                    $(".cloudSmall").css('-webkit-animation-name','bigFly');
                    $(".cloudBig").css('-webkit-animation-name','smallFly');
                    _flagCloud=false;
                    }
                else{
                    $(".cloudSmile").css('-webkit-animation-name','smileFly');
                    $(".cloudBig").css('-webkit-animation-name','bigFly');
                    $(".cloudSmall").css('-webkit-animation-name','smallFly');
                    _flagCloud=true;
                }
            });
            $(".kidBig").bind('touchstart',function(){
                if(_flagKid==true){
                    $(".kidBig").css('-webkit-animation-name','kidFly1');
                    _flagKid=false;
                }
                else{
                    $(".kidBig").css('-webkit-animation-name','kidFly2');
                    _flagKid=true;
                }
            });
            $(".logo").bind('touchstart', function(){
                if(_flagLogo==true){
                    $(".logo").css('-webkit-animation-name','logo1');
                    _flagLogo=false;
                }
                else{
                    $(".logo").css('-webkit-animation-name','logo2');
                    _flagLogo=true;
                }
            })
            $(".play").bind('touchstart', function(){
                $(".play").css('-webkit-animation-name','play');
                _self.clear();
                var p = setTimeout(function(){
                    curPage = 1;
                    menu.create();
                },1000);
            });
            $(".hairLeft").bind('webkitAnimationEnd',function(){
                if(_flagHair==true){
                    $(".hairLeft").css('-webkit-animation-name','hairFly2');
                    $(".hairRight").css('-webkit-animation-name','hairFly1');
                    _flagHair=false;
                }
                else{
                    $(".hairLeft").css('-webkit-animation-name','hairFly1');
                    $(".hairRight").css('-webkit-animation-name','hairFly2');
                    _flagHair=true;
                }
            })
        },100)
    }
    this.clear = function(){
        var t = setTimeout(function(){
            $("#stage").css({
                webkitOpacity:'0.0',
            webkitTransform: 'translate3d(0px,0px,0px)',
            });
        },500);
        var t = setTimeout(function(){
                    $("#stage").text("");
                },1000);
    }
}

//Class stageMenu
function Menu(){
    this.create = function(){
        var html = $("#menuStage").html();
        $("#stage").html(html);
        var back = new BackBtn(menu,index);
        $("#stage").css({
            webkitOpacity:'1.0',
            webkitTransform: 'translate3d(0px,0px,0px)',
            });
        init_menu();
    }
    
    this.clear = function(){
        $("#stage").text("");
    }
}

//Class stagePlay
function Play(){
        this.create = function(){
        var m=0;
        var s=0;
        $.each(data,function(){
            if(this.text==text){
                s = (this.time/1000)%60;
                m = parseInt((this.time/1000)/60);
            }
        })
        if(m<10)    m='0'+m;
        if(s<10)    s='0'+s;
        $("#stage").append('<div id="stagePlay"></div>');
        $("#stagePlay").append('<div class="monitor"> </div>');
        $("#stagePlay").append('<div class="clock"><div class="time">00:00</div><div class="timeRecord">'+m+':'+s+'</div></div>');
        $("#stagePlay").append('<div class="text-bar-container"><div id="text_bar"></div></div>');
        $("#stagePlay").append('<div class="timeStart"> </div>');
        $('.monitor').append('<img class="image" id="picture" src="'+img+'"/>');
        $("#stage").css({
            webkitOpacity:'1.0',
            webkitTransform: 'translate3d(0px,0px,0px)',
            });
        var i=3;
        var numAudio = new Audio();
        var s = setInterval(function(){
            console.log(i);
            if(i==0){
                numAudio = new Audio('sound/batdau.m4a');
                numAudio.play();
                clearInterval(s);
                $('.timeStart').css({
                    webkitTransition: '100ms ease-in',
                    webkitTransform: 'scale(0,0)'
                });
                init(text);
                bgmusic.play();
            }
            else{
                $('.timeStart').css('background','url(images/Play/'+i+'.png) no-repeat');
                $('.timeStart').css({
                    webkitTransition: '0ms ease-in',
                    webkitTransform: 'scale(3,3)'
                });
                numAudio = new Audio('sound/'+i+'.m4a');
                numAudio.play();
                setTimeout(function(){
                        $('.timeStart').css({
                            webkitTransition: '500ms ease-in',
                            webkitTransform: 'scale(0,0)'
                        });
                    },100);
            }
            i--;
        },1000);
    };
    this.clear = function(){
        time.stopTime();
        $("#stage").text("");
        bgmusic.pause();
    }
}

// Init funciont
function init(text){
    //var picAudio = new Audio('sound/'+text+'.mp3');
    var picAudio = new Audio('sound/fish.mp3');
    $("#picture").bind('touchstart',function(){
        picAudio.play();
    })
    var s = new stagePlay(text);
    time.startTime();
}

// Class stagePlay
function stagePlay(text){
    this.pieces = new Array();
    
    //Create Back Button
    var back = BackBtn(play,menu)
    this.pieces.push(back);
    
    // Create Kid
    var kid =  new Kid();
    this.pieces.push(kid);
    kid.show(textQ);
    
    //Create Menu Bottom
    var mBottom = new MenuBottom();
    this.pieces.push(mBottom);
    
    // Create Textplus with Random some symbol
    var textplus=text;
    var len=text.length;
    var string="abcdefghijklmnopqrstuvwxyz";
    for(var i=0;i<(len/3);i++){
        textplus+=string[Math.floor(Math.random()*26)];
    }
    console.log(textplus);
    
    //Create Text Bar
    var bar = new TextBar({
        stagePlay:this,
        text:text
    });
    this.pieces.push(bar);
    
    var barBottom =  new Bar();
    this.pieces.push(barBottom);
   
    
    //Create Text Box
    for(var i=0;i<len;i++){
        textBox[i] = new DraggableBox({
            text:text[i],
            count:i,
            stagePlay:this
        });
        this.pieces.push(textBox[i]);
    }
    
    var plusLen = textplus.length;
    
    //Create textPlace
    var top = 200;
    var left = 0;
    var count = 0;
    for(var i=0;i<plusLen;i++){
    	if(i==parseInt(plusLen/2)){
    		count=0;
    	}
        if(count%3==0&&count!=0){
            top+=81;
            if(i>plusLen/2){
                left=720;
            }
            else left=0;
        }
        if(i==parseInt(plusLen/2)){
            left=720;
            top=200;
        }
        count++;
        textPlace[i]   =   new TextPlace({
            place:{
                top:top+randomMidded(30, 50),
                left:left+randomMidded(30, 50)
            },
            stagePlay:this
        });
        this.pieces.push(textPlace[i]);
        left+=81;
    }
    
    // Put Draggable to textPlace 
    var arr = new Array;
    var j=0;
    count=1;
    for(var i=0;i<plusLen;i++){
    	j=randomMidded(0,plusLen-count);
        var piece = new DraggablePiece({
            count:i,
            text: text,
            txt: textplus[i],
            place: textPlace[j].place,
            stagePlay: this
        });
        textPlace[j]._flag=piece.id;
        textPlace.splice(j,1);
        count++;
        this.pieces.push(piece);
    }
}

// Time Class
function Time(){
    var time=0;
    var m=0;
    var s=0;
    var start;
    var _self = this;
    this.startTime  =    function(){
        time=0;
        start = setInterval(function(){
            if(m>=60)    {
               _self.stopTime();
               var f = new Finish({
                   time: _self.getTime(),
                   text: 'Game over',
                   title: 'Hết giờ',
                   point: 0,
                   star: 0,
               });
               f.show();
            }
            else{
                time+=1000;
                m=parseInt((time/1000)/60);
                s=(time/1000)%60;
                if(m<10)    m='0'+m;
                if(s<10)    s='0'+s;
                $(".time").text(m+":"+s);
            }
        },1000);
    }
    this.stopTime   =   function (){
        clearInterval(start);
    }
    this.getTime    =   function(){
        return time;
    }
}

//  DraggableBox Class - Check place DraggablePiece Object dragg
function DraggableBox(config){
    this.stagePlay=config.stagePlay;
    this.text=config.text;
    this.place = {
        top:$("#box-"+this.text+"-"+config.count+"").offset().top,
        left:$("#box-"+this.text+"-"+config.count+"").offset().left
    };
    this._flag=0;
}

//  randomMidded function - create number midded min and max
function    randomMidded(min,max){
    return Math.floor(Math.random()*(max-min)+min);
}

// TextPlace Class - create place for DraggablePiece Object
function TextPlace(config){
    this.stagePlay=config.stagePlay;
    this.place = config.place;
    this._flag=0;
}

//TextBar Class -  create DraggableBox bar
function TextBar(config){
    this.stagePlay=config.stagePlay;
    this.text=config.text;
    var len = this.text.length;
    for(var i=0;i<len;i++){
            $("#text_bar").append("<div class='text-item' id='box-"+this.text[i]+"-"+i+"' style='background-position: -"+get_symbol(this.text[i])*81+"px -81px;'></div>");
    }
}

// Calcul Point
function calPoint(time,textLen){
    return (3600000-time)/100+textLen*100;
}

// Calcul Star
function calStar(point){
	if(point<=34000)
    	return 0;
    if(point>34000&&point<=35000)
    	return 1;
    if(point>35000&&point<=36000)
    	return 2;
    if(point>36000)
    	return 3;
}

//DraggablePiece Class
function DraggablePiece(config){
    this.text = config.text;
    this.txt = config.txt;
	this.id = "piece-"+config.txt+"-"+config.count;
	this.stagePlay = config.stagePlay;
    this.place = config.place;
	this.x = -get_symbol(config.txt)*(81);
	var _self = this;
	this.audio =  new Audio('items/'+config.txt.toUpperCase()+'.m4a');
	$("#stagePlay").append("<div style='position:absolute; top:0px; left:0px; z-index:6; -webkit-transform: translate3d("+this.place.left+"px,"+this.place.top+"px,0px);'><div style='position:absolute; -webkit-transform: scale(0.8,0.8); background:url(images/Play/sign.png) "+this.x+"px 0px;width:76px;height:76px' id='"+this.id+"'></div><div>");
	this.domObject = document.getElementById(this.id);

	var touchstartHandler = function(e){
	    _self.audio.play();
	    for(var i=0;i<textBox.length;i++){
    	    if(e.changedTouches[0].clientY>textBox[i].place.top&&e.changedTouches[0].clientY<(textBox[i].place.top+76)&&e.changedTouches[0].clientX>textBox[i].place.left&&e.changedTouches[0].clientX<(textBox[i].place.left+76)){
    	        textBox[i]._flag=0;
    	        this.text_placeOld=i;
    	        break;
            }
    	    this.text_placeOld=false;
	    }
	    this.text_styleOld  =   {
	            webkitTransform: e.target.style.webkitTransform
	    }
	    this.parent_styleOld  =   {
                webkitTransform: e.target.parentNode.style.webkitTransform
        }
	    e.target.parentNode.style.webkitTransform = 'translate3d('+(e.changedTouches[0].clientX-40)+'px,'+(e.changedTouches[0].clientY-40)+'px,0px)';
	    e.target.style.webkitTransform = 'scale(1.2, 1.2)';
    	console.log("touchstart ",e);
	}
	
	var touchmoveHandler = function(e){
		console.log("touchmove ",e);
		e.target.parentNode.style.webkitTransform = ' translate3d('+(e.changedTouches[0].pageX-40)+'px,'+(e.changedTouches[0].pageY-40)+'px,0px)';
		e.target.style.webkitTransform = 'scale(1.2, 1.2)';
	}

	var touchendHandler = function(e){
	    console.log(e.changedTouches[0].clientY);
	    for(var i=0;i<textBox.length;i++){
    	    if(e.changedTouches[0].clientY>textBox[i].place.top&&e.changedTouches[0].clientY<(textBox[i].place.top+76)&&e.changedTouches[0].clientX>textBox[i].place.left&&e.changedTouches[0].clientX<(textBox[i].place.left+76)){
    	        if(textBox[i]._flag==0){
    	            e.target.style.webkitTransform = 'scale(1.0, 1.0)';
    	            e.target.parentNode.style.webkitTransform =  'translate3d('+textBox[i].place.left+'px,'+textBox[i].place.top+'px,0px)';
        	        textBox[i]._flag=e.target.id;
    	        }
    	        else{
    	            document.getElementById(textBox[i]._flag).style.webkitTransform=this.text_styleOld.webkitTransform;
    	            document.getElementById(textBox[i]._flag).parentNode.style.webkitTransform = this.parent_styleOld.webkitTransform;
    	            e.target.style.webkitTransform = 'scale(1.0,1.0)';
    	            e.target.parentNode.style.webkitTransform='translate3d('+textBox[i].place.left+'px,'+textBox[i].place.top+'px,0px)';
                    if(textBox[this.text_placeOld])
                        textBox[this.text_placeOld]._flag=textBox[i]._flag;
                    textBox[i]._flag=e.target.id;
    	        }
    	        dragAudio.play();
    	        
    	        // If drag true One able
    	        if(checkOne(_self.txt,_self.text,i)){
    	            _self.audio.play();
    	        }
    	        console.log("touchend ",e);
    	        check(textBox,config.text);
    	        return;
    	    }
	    }
	    dragAudio.play();
	    e.target.style.webkitTransform = 'scale(0.8,0.8)';
	    console.log("touchend ",e);
	    check(textBox,config.text);
		return;
	}
	this.domObject.addEventListener("touchstart", touchstartHandler);
	this.domObject.addEventListener("touchmove", touchmoveHandler);
	this.domObject.addEventListener("touchend", touchendHandler);
	this.domObject.addEventListener("touchcancel", touchendHandler);
}

//  GET place of symbol from alpha char
function    get_symbol(symbol){
    var string="abcdefghijklmnopqrstuvwxyz";
    var len = string.length;
    for(var i=0;i<len;i++){
        if(symbol==string[i])   return i;
    }
    return false;
}
// Bar class
function Bar(){
    var _self = this;
    $("#stagePlay").append('<div class="bar"></div>');
    this.push = function(element){
        $(".bar").append(element);
    }
}
// Menu Bottom Class
function MenuBottom(){
    var _self = this;
    this.shown = false;
    $("#stagePlay").append('<div id="menuBottom"><div id="mbt-container"></div><div class="menuBottom-btn"><div></div></div></div>');
    $("#menuBottom").find(".menuBottom-btn").bind('touchstart', function(){
        if(_self.shown){
            _self.hide();   
        }else{
            _self.show();
        }
    });
    document.getElementById("menuBottom").style.webkitTransition = '200ms ease-in';
    
    this.push = function(element){
        $("#mbt-container").append(element);
    }
    
    this.show = function(){
        document.getElementById("menuBottom").style.webkitTransform = 'translate3d(0px,-200px,0px)';
        document.getElementsByClassName("menuBottom-btn")[0].style.top = '45px';
        document.getElementsByClassName("menuBottom-btn")[0].style.webkitTransform = 'rotate(180deg)';
        _self.shown = true;
    }
    
    this.hide = function(){
        document.getElementById("menuBottom").style.webkitTransform = 'translate3d(0px,0px,0px)';
        document.getElementsByClassName("menuBottom-btn")[0].style.top = '20px';
        document.getElementsByClassName("menuBottom-btn")[0].style.webkitTransform = 'rotate(0deg)';
        _self.shown = false;
    }
}

//CheckOne true drag
function checkOne(txt,text,i){
    if(txt==text[i]){
        return true;
    }
    return false;
}

//Check true answer
function check(textBox,text){
    var _flag=0;
    var len = text.length;
    for(var i=0;i<len;i++){
        console.log(textBox[i]._flag[6]);
        if(textBox[i]._flag[6]==text[i])
            _flag+=1;
    }
    if(_flag==textBox.length){
        time.stopTime();
        var point = calPoint(time.getTime(),len);
        var f = new Finish({
            time: time.getTime(),
            text: text,
            point: point,
            star: calStar(point),
        });
        f.show();
        $.each(data,function(i){
            if(this.text==text){
                data[i+1].status='unlock';
                if(this.time==0||this.time>time.getTime()){
                    this.time=time.getTime();
                    this.star=calStar(point);
                    $(".finish").append('<div class="perfect"></div>');
                    localStorage['gameData']=JSON.stringify(data);
                    data = JSON.parse(localStorage['gameData']);
                }
            }
        });
        return true;
    }
    return  false;
}

// Kid Class
function Kid(){
    var _self = this;
    $('#stagePlay').append('<div id="kid"></div>');
   
    this.show = function(text){
        console.log(text);
        $('#stagePlay').append('<div class="kid_say"><b>'+text+'</b></div>');
        $('#kid').css({
            webkitTransition: '200ms ease-in',
            webkitTransform: 'translate3d(-250px,0px,0px)'
        })
        var time = 0;
        var delay = setInterval(function(){
            if(time==2){
                $('#kid').css({
                    webkitTransition: '200ms ease-in',
                    webkitTransform: 'translate3d(0px,0px,0px)'
                });
            }
            if(time==3){
                $('.kid_say').css({
                    webkitTransition: '200ms ease-in',
                    webkitTransform: 'scale(1.0,1.0)'
                });
            }
            if(time==10){
                clearInterval(delay);
                time=0;
                $('.kid_say').css({
                    webkitTransition: '200ms ease-in',
                    webkitTransform: 'scale(0.0,0.0)'
                });
            }
            time++;
        },200);
    }
    $('#kid').bind('touchstart', function(){_self.show(textSay+text);});
}

// BackBtn Class
function BackBtn(stageHide,stageShow){
    var _self = this;
    $("#stage").append('<div id="backBtn"></div>');
    
    var back = function(){
        $("#backBtn").unbind();
        $("#backBtn").css('-webkit-transform','rotate(-180deg)');
        $("#stage").css({
            webkitOpacity:'0.0',
            webkitTransform: 'translate3d(-2000px,0px,0px)',
            });
        var t=setTimeout(function(){
            stageHide.clear();
            stageShow.create();
        },1000);
    }
    $("#backBtn").bind('touchstart', back);
}

function Finish(config){
    var _self = this;
    this.time = config.time;
    this.text = config.text;
    this.star = config.star;
    this.point = config.point;
    var m = parseInt((this.time/1000)/60);
    var s = (this.time/1000)%60;
    if(m<10){
        m="0"+m;
    }
    if(s<10){
        s="0"+s;
    }
    
    this.show = function(){
        $("#stage").append('<div class="finish"></div>');
        $(".finish").append('<div class="textFinish">'+this.text.toUpperCase()+'</div>');
        $(".finish").append('<div class="point">'+this.point+'</div>');
        $(".finish").append('<div class="time">'+m+':'+s+'</div>');
        $(".finish").append('<div class="starBig">'
                +'<div class="star-item" id="starBig-1"></div>'
                +'<div class="star-item" id="starBig-2"></div>'
                +'<div class="star-item" id="starBig-3"></div>'
                +'</div>');
        for(var i=1; i<=this.star;i++){
            $("#starBig-"+i).css('background-position-y','0px');
        }
        $(".finish").append('<div class="btnFinish">'
                +'<div class="btnNext"></div>'
                +'<div class="btnReplay"></div>'
                +'<div class="btnMenu"></div>'
                +'</div>');
        var tmp = setTimeout(function(){
            $(".finish").css('-webkit-transform','scale(1.0,1.0)');
        },100);
        $(".btnNext").bind('touchstart', function(){
            if(_self.point!=0){
            $("#stage").css({
                webkitOpacity:'0.0',
                });
            $(".btnNext").css({
                webkitTransition: '500ms ease-out',
                webkitTransform:'scale(2,2)',
            });
            var t=setTimeout(function(){
                $(".btnNext").css({
                    webkitTransition: '500ms ease-out',
                    webkitTransform:'scale(1,1)',
                });
                    _self.clear();
                    $.each(data, function(i){
                        if(this.text==_self.text){
                            text=data[i+1].text;
                            img=data[i+1].picture;
                            textQ=data[i+1].textQ;
                            textSay=data[i+1].textSay;
                            }
                        });
                    play.create();
                },500);
            }
            else{
                $(".btnNext").css({
                    webkitTransition: '500ms ease-out',
                    webkitTransform:'scale(2,2)',
                });
                var t=setTimeout(function(){
                    $(".btnNext").css({
                        webkitTransition: '500ms ease-out',
                        webkitTransform:'scale(1,1)',
                    });
                    alert("Game over can't next level!");
                },1000);
                }
            });
        $(".btnReplay").bind('touchstart', function(){
            $("#stage").css({
                webkitOpacity:'0.0',
                });
            $(".btnReplay").css({
                webkitTransition: '500ms ease-out',
                webkitTransform:'scale(2,2)',
            });
            var t=setTimeout(function(){
                $(".btnReplay").css({
                    webkitTransition: '500ms ease-out',
                    webkitTransform:'scale(1,1)',
                });
                _self.clear();
                play.create();
                },1000);
            });
        $(".btnMenu").bind('touchstart', function(){
            $("#stage").css({
                webkitOpacity:'0.0',
                });
            $(".btnMenu").css({
                webkitTransition: '500ms ease-out',
                webkitTransform:'scale(2,2)',
            });
            var t=setTimeout(function(){
                $(".btnMenu").css({
                    webkitTransition: '500ms ease-out',
                    webkitTransform:'scale(1,1)',
                });
                _self.clear();
                menu.create();
                },1000);
            });
        }
    this.clear = function(){
        $("#stage").text("");
        play.clear();
    }
}
